﻿using System;
using System.Windows.Forms;
using SpeechLib;
using WoWTimer.Classes;

namespace WoWTimer
{
    public partial class OptionsForm : Form
    {
        readonly Options _options;

        public OptionsForm(Options options)
        {
            InitializeComponent();

            if (options == null)
                throw new ArgumentNullException("options");

            _options = options;

            textBoxLuaLocation.Text = _options.LuaDir;
            numericUpDownDefaultAlarmTime.Value = _options.Remaining;
            trackBarVoiceVolume.Value = _options.Volume / 10;
            textBoxSpeachText.Text = _options.SpeachText;

            labelVolumePercent.Text = _options.Volume + "%";
        }

        private void buttonBrowseLuaLocation_Click(object sender, EventArgs e)
        {
            OpenFileDialog luaDirDialog = new OpenFileDialog { Multiselect = false };
            luaDirDialog.ShowDialog();
            if (luaDirDialog.FileName != null)
            {
                textBoxLuaLocation.Text = luaDirDialog.FileName;
                _options.LuaDir = luaDirDialog.FileName;
            }
        }

        private void TrackBarVoiceVolume_Scroll(object sender, EventArgs e)
        {
            labelVolumePercent.Text = (trackBarVoiceVolume.Value * 10) + "%";
            _options.Volume = (trackBarVoiceVolume.Value * 10);
        }

        private void numericUpDownDefaultAlarmTime_ValueChanged(object sender, EventArgs e)
        {
            _options.Remaining = (int)numericUpDownDefaultAlarmTime.Value;
        }

        private void buttonVoiceTest_Click(object sender, EventArgs e)
        {
            string speakText = textBoxSpeachText.Text;

            if (speakText.Contains("$ZONE$"))
                speakText = speakText.Replace("$ZONE$", "Wintergrasp");

            if (speakText.Contains("$REALM$"))
                speakText = speakText.Replace("$REALM$", "selected Realm");

            if (speakText.Contains("$REMAINING$"))
                speakText = speakText.Replace("$REMAINING$", _options.Remaining.ToString());

            _options.SpeachText = speakText;

            try
            {
                const SpeechVoiceSpeakFlags spFlags = SpeechVoiceSpeakFlags.SVSFlagsAsync;
                SpVoice voice = new SpVoice { Volume = trackBarVoiceVolume.Value * 10 };
                voice.Speak(speakText, spFlags);
            }
            catch (Exception)
            {
                MessageBox.Show("Speak error", "WintergraspTimer", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void buttonApplyOptions_Click(object sender, EventArgs e)
        {
            OptionsReadWrite.Save(MainForm.ConfigFile, _options);
        }

        private void buttonCloseOptions_Click(object sender, EventArgs e)
        {
            Close();
        }
    }
}
